import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavBar, Input, Button, Avatar, Toast, ImageUploader, Image, ImageViewer } from 'antd-mobile';
import { useParams, history } from 'umi';
import { SendOutline, PictureOutline, LeftOutline } from 'antd-mobile-icons';
import request from '@/utils/request';
import styles from './index.less';

interface Message {
    id: number;
    from_user_id: number;
    to_user_id: number;
    content: string;
    msg_type: 'text' | 'image' | 'file';
    is_read: boolean;
    created_at: string;
    from_username: string;
    to_username: string;
}

interface ChatUser {
    id: number;
    username: string;
    real_name: string;
    service_name?: string;
    avatar_url: string;
    status: 'online' | 'offline' | 'busy';
}

interface ApiResponse<T> {
    code: number;
    data: T;
}

interface UserInfo {
    role_name: string;
}

const Chat: React.FC = () => {
    const { targetId } = useParams<{ targetId: string }>();
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputValue, setInputValue] = useState('');
    const [targetUser, setTargetUser] = useState<ChatUser | null>(null);
    const [currentUser, setCurrentUser] = useState<any>(null);
    const [ws, setWs] = useState<WebSocket | null>(null);
    const messagesEndRef = useRef<HTMLDivElement>(null);

    // 获取当前用户信息和目标用户信息
    useEffect(() => {
        const fetchUsers = async () => {
            try {
                const userRes = await request.get<any, ApiResponse<UserInfo>>('/user/info');
                if (userRes.code === 200) {                    
                    setCurrentUser(userRes.data);
                    // 根据当前用户角色决定如何获取目标用户信息
                    if (userRes.data.role_name === 'customer_service') {
                        const targetRes = await request.get<any, ApiResponse<ChatUser>>(`/user-consultations/${targetId}`);
                        console.log(targetRes);                   
                        if (targetRes.code === 200) {
                            setTargetUser(targetRes.data);
                        }
                    } else {
                        const targetRes = await request.get<any, ApiResponse<ChatUser>>(`/customer-service/${targetId}`);
                        console.log(targetRes);
                        
                        if (targetRes.code === 200) {
                            setTargetUser(targetRes.data);
                        }
                    }
                }
            } catch (error) {
                console.error('Failed to fetch users:', error);
            }
        };

        fetchUsers();
    }, [targetId]);

    // 获取聊天记录
    useEffect(() => {
        const fetchChatHistory = async () => {
            try {
                const res = await request.get<any, ApiResponse<Message[]>>('/chat-history', {
                    params: {
                        targetId,
                        limit: 50
                    }
                });
                if (res.code === 200) {
                    setMessages(res.data);
                    scrollToBottom();
                }
            } catch (error) {
                console.error('Failed to fetch chat history:', error);
            }
        };

        if (targetId) {
            fetchChatHistory();
        }
    }, [targetId]);

    // WebSocket 连接和消息处理
    useEffect(() => {
        const token = localStorage.getItem('token');
        const wsClient = new WebSocket(`ws://localhost:3001/ws?token=${token}`);
        let heartbeatInterval: NodeJS.Timeout;

        wsClient.onopen = () => {
            console.log('WebSocket connected');
            heartbeatInterval = setInterval(() => {
                wsClient.send(JSON.stringify({ type: 'ping' }));
            }, 30000);
        };

        wsClient.onmessage = (event) => {
            const message = JSON.parse(event.data);
            if (message.type === 'chat' && 
                (message.data.from_user_id === Number(targetId) || 
                 message.data.to_user_id === Number(targetId))) {
                setMessages(prev => [...prev, message.data]);
                scrollToBottom();
            }
        };

        setWs(wsClient);

        return () => {
            clearInterval(heartbeatInterval);
            wsClient.close();
        };
    }, [targetId]);

    // 对消息进行排序，确保最新的消息在最下方
    const sortedMessages = useMemo(() => {
        return [...messages].sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
    }, [messages]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    // 发送消息
    const handleSend = () => {
        if (!inputValue.trim() || !ws || !currentUser || !targetUser) return;

        const message = {
            type: 'chat',
            to: Number(targetId),
            content: inputValue.trim(),
            msgType: 'text'
        };

        try {
            ws.send(JSON.stringify(message));
            
            // 添加到本地消息列表
            const newMessage: Message = {
                id: Date.now(),
                from_user_id: currentUser.id,
                to_user_id: Number(targetId),
                content: inputValue.trim(),
                msg_type: 'text',
                is_read: false,
                created_at: new Date().toISOString(),
                from_username: currentUser.username,
                to_username: targetUser.username
            };

            setMessages(prev => [...prev, newMessage]);
            setInputValue('');
            scrollToBottom();
        } catch (error) {
            console.error('Failed to send message:', error);
            Toast.show({
                icon: 'fail',
                content: '发送失败，请重试'
            });
        }
    };

    // 处理图片上传
    const handleImageUpload = async (file: File) => {
        try {
            const formData = new FormData();
            formData.append('file', file);
            
            const res = await request.post<any, ApiResponse<{ url: string }>>('/upload/image', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                }
            });

            if (res.code === 200 && currentUser && targetUser) {
                const message = {
                    type: 'chat',
                    to: Number(targetId),
                    content: res.data.url,
                    msgType: 'image'
                };

                ws?.send(JSON.stringify(message));
                
                const newMessage: Message = {
                    id: Date.now(),
                    from_user_id: currentUser.id,
                    to_user_id: Number(targetId),
                    content: res.data.url,
                    msg_type: 'image',
                    is_read: false,
                    created_at: new Date().toISOString(),
                    from_username: currentUser.username,
                    to_username: targetUser.username
                };

                setMessages(prev => [...prev, newMessage]);
                return { url: res.data.url };
            }
            throw new Error('上传失败');
        } catch (error) {
            Toast.show({
                icon: 'fail',
                content: '图片上传失败'
            });
            return { url: '' };
        }
    };

    const getDisplayName = (user: ChatUser) => {
        return user.service_name || user.real_name || user.username;
    };

    return (
        <div className={styles.chatContainer}>
            <div className={styles.navbar}>
                <LeftOutline className={styles.backIcon} onClick={() => history.back()} />
                <span className={styles.title}>
                    {targetUser ? getDisplayName(targetUser) : '聊天'}
                    {targetUser?.status === 'offline' && 
                        <span className={styles.offlineTag}>离线</span>
                    }
                </span>
            </div>

            <div className={styles.messageList}>
                {sortedMessages.map((msg) => (
                    <div 
                        key={msg.id}
                        className={`${styles.messageItem} ${
                            msg.from_user_id !== targetUser?.id ? styles.sent : styles.received
                        }`}
                    >
                        <Image
                            src={msg.from_user_id !== targetUser?.id 
                                ? currentUser?.avatar_url 
                                : targetUser?.avatar_url
                            }
                            className={styles.avatar}
                            fit='cover'
                            onClick={(e) => {
                                e.stopPropagation();
                                const imgUrl = msg.from_user_id !== targetUser?.id 
                                    ? currentUser?.avatar_url 
                                    : targetUser?.avatar_url;
                                if (imgUrl) {
                                    ImageViewer.show({
                                        image: imgUrl
                                    });
                                }
                            }}
                        />
                        <div className={styles.messageContent}>
                            {msg.msg_type === 'text' ? (
                                <div className={styles.messageText}>
                                    {msg.content}
                                </div>
                            ) : (
                                <div className={styles.messageImage}>
                                    <Image
                                        src={msg.content}
                                        alt="聊天图片"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            ImageViewer.show({
                                                image: msg.content
                                            });
                                        }}
                                    />
                                </div>
                            )}
                            <div className={styles.messageTime}>
                                {new Date(msg.created_at).toLocaleTimeString()}
                                {msg.is_read && <span className={styles.readStatus}>已读</span>}
                            </div>
                        </div>
                    </div>
                ))}
                <div ref={messagesEndRef} />
            </div>

            <div className={styles.inputArea}>
                <ImageUploader
                    value={[]}
                    onChange={() => {}}
                    upload={handleImageUpload}
                    maxCount={1}
                    onCountExceed={() => {}}
                    className={styles.imageUploader}
                >
                    <Button className={styles.uploadButton}>
                        <PictureOutline />
                    </Button>
                </ImageUploader>
                <Input
                    className={styles.input}
                    placeholder="请输入消息"
                    value={inputValue}
                    onChange={setInputValue}
                    onEnterPress={handleSend}
                    disabled={targetUser?.status === 'offline'}
                />
                <Button
                    className={styles.sendButton}
                    onClick={handleSend}
                    disabled={targetUser?.status === 'offline'}
                >
                    <SendOutline />
                </Button>
            </div>
        </div>
    );
};

export default Chat; 